package com.powerunion.datacollection.service;

import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.ApproveWorkItemDao;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.model.ActivityInstance;
import com.powerunion.datacollection.model.ApproveActivityInstance;
import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.util.log.LogHelper;

public class ApproveWorkItemManager {
	private static Logger logger = LogHelper.getInstance().getLogger(
			ApproveWorkItemManager.class);
	private ApproveWorkItemDao dao = null;

	public ApproveWorkItemManager() {
		super();
		this.dao = (ApproveWorkItemDao) DaoFactory.getInstance().getDao(
				ApproveWorkItemDao.class);
	}

	public boolean initApproveWork(ApproveActivityInstance activityInfo,
			String formId) throws Exception {

		// 参数为空
		if (activityInfo == null) {
			String[] args = { "activityInfo" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter activityInfo NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		// 参数为空
		if (StringUtils.isEmpty(formId)) {
			String[] args = { "formId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter formId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.initApproveWork(activityInfo, formId);
	}

	public String findApproveWorkByUser(String userCode) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(userCode)) {
			String[] args = { "userCode" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter userCode NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		List aws = this.dao.findApproveWorkByUser(userCode);
		JSONArray jsonArr = JSONArray.fromObject(aws);
		String result = "{results:" + jsonArr + "}";
		return result;
	}

	public boolean updateState4Act(int state, String id) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.updateState4Act(state, id);
	}

	public boolean suspendApproveWork(String procId) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.suspendApproveWork(procId);
	}

	public boolean resumeApproveWork(String procId) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.resumeApproveWork(procId);
	}

	public List findApproveWorkIdByActivityId(String activityId)
			throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(activityId)) {
			String[] args = { "activityId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter activityId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.findApproveWorkIdByActivityId(activityId);
	}

	/**
	 * 提交报送数据
	 * 
	 * @param actId
	 *            报送环节id
	 * @param approveWorkId
	 *            审批任务id
	 * @return
	 * @throws Exception
	 */
	public String submission(String actId, String approveWorkId,
			String nextActivityId,String dynamicApproveUsers) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (StringUtils.isEmpty(approveWorkId)) {
			String[] args = { "approveWorkId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter approveWorkId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		String result = "";
		boolean flag = false;
		// 判断该任务是否已经完成或被隐藏
		flag = this.dao.iApproveWorkCommit(approveWorkId);
		if (flag) {// 该任务是否被隐藏或已经完成
			result = "该任务已经结束！不能提交！";
			return result;
		}
		ApproveWorkItem awi = this.dao.getByKey(approveWorkId);

		ActivityManager activityManager = new ActivityManager();
		// 更新前一采集步骤的状态
		SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
		/**
		 * 如果是不同意返回修改,则直接把同个审批步骤中的其他审批任务隐藏
		 * 
		 */
		if (awi.getApproveMindType() == Constants.APPROVE_MIND_TYPE_BACKTRACK) {
			// 隐藏同个审批步骤中的其他审批任务
			this.dao
					.hideApproveWork(actId, awi.getStaffId(), awi.getPreActId());
			// 更新该审批任务的状态为"等待返回修改的数据"状态
			this.dao.updateState4User(Constants.APPROVE_WAIT_UPDATE,
					approveWorkId);
			// 获取前一个步骤的类型
			int actType2 = awi.getPreActType();
			if (actType2 == Constants.APPROVE_STEP_TYPE) {// 审批类型
				// 更新前一个审批步骤的状态
				flag = this.dao.updateState4Act(Constants.APPROVE_DISACCORD,
						awi.getPreActId());
				String submiUser = awi.getSubmiUser();
				int fisrtIndex = submiUser.indexOf(";");
				int lastIndex = submiUser.lastIndexOf(";");
				if (fisrtIndex != -1 && lastIndex != -1) {
					submiUser = submiUser.substring(fisrtIndex + 1, lastIndex);
				}
				// 得到上一步骤的审批步骤
				ApproveWorkItem preSubmiUser = this.dao.getByKey(submiUser);
				int prepreType = preSubmiUser.getPreActType();
				// 更新上一步骤的子步骤为等待审批状态
				if (prepreType == Constants.APPROVE_STEP_TYPE) {
					this.dao.updateState4Act(Constants.APPROVE_WAIT4Approve,
							preSubmiUser.getPreActId());
				} else if (prepreType == Constants.COLLECTION_STEP_TYPE) {
					swm.updateState(Constants.SUBMISSION_WAIT4Approve,
							preSubmiUser.getPreActId());
				}
				// 更新上一步骤的流程实例节点状态为等待审批
				activityManager.updateActivityState(Constants.ACTIVITY_WAIT,
						preSubmiUser.getPreActId());

			} else if (actType2 == Constants.COLLECTION_STEP_TYPE) {// 报送类型

				// 得到该采集步骤的类型
				int swimType = swm.getActivityType(awi.getPreActId());
				if (swimType == Constants.SUBMISSION_TYPE_MULTI) {
					// 如果是多人类型 把其他人的任务状态改成等待同步状态
					swm.updateState(Constants.SUBMISSION_SYNCHRO_WAIT, awi
							.getPreActId());
					// 同时更新审批没通过的提交者的任务状态
					swm.updateState4User(Constants.APPROVE_DISACCORD, awi
							.getApproveSubwork());
				} else {
					flag = swm.updateState(Constants.SUBMISSION_DISACCORD, awi
							.getPreActId());
				}
			}
			// 更新上报步骤的流程节点的状态
			activityManager.updateActivityState(Constants.ACTIVITY_UNSUB, awi
					.getPreActId());

		} else {
			// 判断是否所有的子节点都已经上报了数据
			boolean isAll = this.dao.isAllSubActHaveSubmission(actId);
			if (isAll) {
				// 需要判断环节类型来根据规则是否允许提交该上报数据
				boolean ipermit = this.dao.submissionRule(actId, awi
						.getStaffId());
				if (ipermit) {// 允许
					ActivityManager am = new ActivityManager();
					// 根据提交数据的审批步骤得到上级的审批步骤
					ApproveActivityInstance aai = null;
					ApproveActivityInstance parentActivity = null;
					if (StringUtils.isEmpty(nextActivityId)) {
						aai = am.getParentActivity(actId);
					} else {
						parentActivity = am.getParentActivity(actId);
						aai = am.getApproveActivityInstance(nextActivityId);
					}

					if (aai.getActivityType() == Constants.START_STEP_TYPE) {// 如果是发起人节点
						// 更新任务实例状态为完成
						CollectionTaskInstanceManager cim = new CollectionTaskInstanceManager();
						cim.updateTaskInstanceStateByProc(awi.getProcId(),
								Constants.TASK_COMPLETE);
						if (awi.getType() == Constants.APPROVE_TYPE_SINGLE) {
							// 如果该审批步骤是单人类型而有设了多个审批人，又因为只会有一个人提交数据，所以把该审批步骤的其他非提交人的任务隐藏掉
							this.dao.hideApproveWork(actId, awi.getStaffId(),
									awi.getPreActId());
							// 然后设置当前这个提交人在这个审批步骤下的所有任务的状态为完成状态
							flag = this.dao.updateState4UserCode(
									Constants.APPROVE_COMPLETE, actId, awi
											.getStaffId());
						} else if (awi.getType() == Constants.APPROVE_TYPE_MULTI) {
							this.dao.updateState4Act(
									Constants.APPROVE_COMPLETE, actId);
						}
						// 更新当前流程步骤为已完成状态
						activityManager.updateActivityState(
								Constants.ACTIVITY_COMPLETE, actId);

					} else {
						// 如果之前已经有审批过 属于是要求被重新填写再提交的，则把先前的审批任务隐藏，重新生成新的任务
						this.dao.hideAllApproveWork(actId);
						if (awi.getType() == Constants.APPROVE_TYPE_SINGLE) {
							aai.setSubmiUser(";" + approveWorkId + ";");// 数据库数据格式为";id;"
						} else if (awi.getType() == Constants.APPROVE_TYPE_MULTI) {
							// 获取该审批步骤下所有的审批任务的id
							String approveWorkIds = this.dao
									.getAllApproveWorkIds(actId);
							aai.setSubmiUser(approveWorkIds);
						}
						aai.setPreActivityId(actId);
						aai.setPreActivityType(Constants.APPROVE_STEP_TYPE);
						
						if(!StringUtils.isEmpty(dynamicApproveUsers)){
							aai.setApproveUserOrurgencyDate(dynamicApproveUsers);
						}
						flag = this.dao.initApproveWork(aai, awi.getFormId());
						flag = this.dao.updateState4Act(
								Constants.APPROVE_WAIT4Approve, actId);
						if (parentActivity != null) {
							if (!parentActivity.getActivityId().equals(
									aai.getActivityId())) {
								// 如果被略过的上级审批步骤只有当前这个子步骤，则设置该审批步骤为隐藏
								int children = activityManager.getChildren(
										parentActivity.getActivityId()).size();
								if (children == 1) {
									activityManager.updateActivityState(
											Constants.ACTIVITY_JUMP_HIDE,
											parentActivity.getActivityId());
								}
								activityManager.reconfigActivityPosition(
										nextActivityId, actId);
							}
						}

						// 更新当前步骤为等待审批状态
						activityManager.updateActivityState(
								Constants.ACTIVITY_WAIT, actId);
					}
					// 更新上报的所有步骤为审批通过状态
					activityManager.updateActivityState4Child(
							Constants.ACTIVITY_COMPLETE, awi.getActId());
					flag = this.updateAllSubAct(awi.getActId());
					if (flag) {
						if (!flag) {
							result = "提交数据失败！";
						}
					} else {
						result = "提交数据失败！";
					}
				} else {
					int acivityType = awi.getType();
					if (acivityType == Constants.APPROVE_TYPE_SINGLE) {
						boolean iSub = this.dao.isSub(actId);
						if (iSub) {
							flag = this.dao.updateState4User(
									Constants.APPROVE_SYNCHRO_WAIT,
									approveWorkId);
							result = "";
						} else {
							result = "其他人已经提交了该审批意见！";
						}

					} else if (acivityType == Constants.APPROVE_TYPE_MULTI) {
						flag = this.dao.updateState4User(
								Constants.APPROVE_SYNCHRO_WAIT, approveWorkId);
						result = "";
					}
				}
			} else {// 如果还有子节点没有上报数据，则转入等待状态
				this.dao.updateState4User(Constants.APPROVE_SYNCHRO_WAIT,
						approveWorkId);

				result = "";
			}
		}
		return result;
	}

	private boolean updateAllSubAct(String actId) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		ActivityManager am = new ActivityManager();
		boolean flag = false;
		// 得到当前审批步骤的子步骤
		List children = am.getChildren(actId);
		for (Iterator iter = children.iterator(); iter.hasNext();) {
			ActivityInstance ai = (ActivityInstance) iter.next();
			int actType = ai.getActivityType();
			int actState = ai.getActState();
			if (actState != Constants.ACTIVITY_UNSUB
					&& actState != Constants.ACTIVITY_JUMP_HIDE) {
				if (actType == Constants.APPROVE_STEP_TYPE) {
					// 更新前一个审批步骤的状态
					flag = this.dao.updateState4Act(Constants.APPROVE_COMPLETE,
							ai.getActivityId());
				} else if (actType == Constants.COLLECTION_STEP_TYPE) {
					// 更新前一采集步骤的状态
					SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
					// 得到该采集步骤的类型
					flag = swm.updateState(Constants.SUBMISSION_COMPLETE, ai
							.getActivityId());
				}
			}

			if (!flag) {
				break;
			}
		}

		return flag;

	}

	public boolean update4User(int state, String id) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.updateState4User(state, id);

	}

	public boolean saveApproveInfo(String approveInfo, String actId,
			String approveWorkId, String nextActivityId,String dynamicApproveUsers) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(approveInfo)) {
			String[] args = { "approveInfo" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter approveInfo NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		JSONObject jo = JSONObject.fromObject(approveInfo);
		ApproveWorkItem aw = (ApproveWorkItem) JSONObject.toBean(jo,
				ApproveWorkItem.class);
		boolean flag = this.dao.saveApproveInfo(aw);

		if (flag) {
			flag = this.dao.updateState4User(Constants.APPROVE, aw.getId());
		}
		if (flag) {
			String result = this.submission(actId, approveWorkId,
					nextActivityId,dynamicApproveUsers);
			if (StringUtils.isEmpty(result)) {
				flag = true;
			} else {
				flag = false;
			}
		}
		return flag;
	}

	public String loadApproveInfo(String id) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		ApproveWorkItem awi = this.dao.getByKey(id);
		JSONObject jsonObject = JSONObject.fromObject(awi);

		String info = "{success:true,data:[" + jsonObject + "]}";
		return info;
	}

	public String approveInfoHistory(String actId, int type) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(actId)) {
			String[] args = { "actId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter actId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		List awim = this.dao.approveInfoHistory(actId, type);
		JSONArray jsonArr = JSONArray.fromObject(awim);
		String result = "{results:" + jsonArr + "}";
		return result;
	}

	public String getSubWorkUsers(String approveWorkId, int workItemType)
			throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(approveWorkId)) {
			String[] args = { "approveWorkId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter approveWorkId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		StringBuffer result = new StringBuffer();
		List subWorkUsers = this.dao.getSubWorkUsers(approveWorkId,
				workItemType);
		// 转化成JSON数组
		JSONArray jsonarr = JSONArray.fromObject(subWorkUsers);
		result.append("{results:").append(jsonarr).append("}");

		return result.toString();

	}

	public boolean hideAllApproveWork(String preActId) throws Exception {

		// 参数为空
		if (StringUtils.isEmpty(preActId)) {
			String[] args = { "preActId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter approveWorkId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.hideAllApproveWork(preActId);
	}

	/**
	 * 查找已办审批任务
	 * 
	 * @param userCode
	 * @return
	 * @throws DaoException
	 */
	public String findCompleteApproveWorkByUser(String userCode)
			throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(userCode)) {
			String[] args = { "userCode" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter userCode NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		List cts = this.dao.findCompleteApproveWorkByUser(userCode);
		JSONArray jsonArr = JSONArray.fromObject(cts);
		String result = "{results:" + jsonArr + "}";
		return result;

	}

	public String findAllApproveWorkByUser(String userCode) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(userCode)) {
			String[] args = { "userCode" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter userCode NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		List cts = this.dao.findAllApproveWorkByUser(userCode);
		JSONArray jsonArr = JSONArray.fromObject(cts);
		String result = "{results:" + jsonArr + "}";
		return result;
	}

	public ApproveWorkItem getByKey(String id) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getByKey(id);
	}

	public boolean saveByTransmit(ApproveWorkItem awi, String receiveUsers)
			throws DaoException {
		// 参数为空
		if (awi == null) {
			String[] args = { "awi" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter awi NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		// 参数为空
		if (StringUtils.isEmpty(receiveUsers)) {
			String[] args = { "receiveUsers" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter receiveUsers NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.saveByTransmit(awi, receiveUsers);
	}

	public boolean iApproveWorkCommit(String id) throws DaoException {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.iApproveWorkCommit(id);
	}
}
